package com.atguigu.flink.chapter11;

import com.atguigu.flink.chapter05.Source.WaterSensor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

/**
 * TODO
 *
 * @author cjp
 * @version 1.0
 * @date 2021/1/27 10:11
 */
public class Flink01_TableAPI_Demo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<WaterSensor> sensorDS = env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                new WaterSensor("sensor_1", 2000L, 20),
                new WaterSensor("sensor_2", 3000L, 30),
                new WaterSensor("sensor_1", 4000L, 40),
                new WaterSensor("sensor_1", 5000L, 50),
                new WaterSensor("sensor_2", 6000L, 60));

        // TODO 1.创建 表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        // TODO 2.将 流 转换成 动态表( pojo的属性名，对应 表的 字段名)
        Table sensorTable = tableEnv.fromDataStream(sensorDS);
        // TODO 3.使用 TableAPI 对动态表 进行 连续查询(  字段名用表达式： $("字段名")   )
        Table resultTable = sensorTable
//                .where("id = 'sensor_1'")
                .where($("id").isEqual("sensor_1"))
                .select($("id"), $("ts"), $("vc"));
        // TODO 4.将 结果表 转成 流
        DataStream<Row> resultDS = tableEnv.toAppendStream(resultTable, Row.class);
        // 每个字段类型都定义：Tuple3<String,Long,Integer>
//        DataStream<Tuple> resultDS = tableEnv.toAppendStream(resultTable, Types.TUPLE(Types.STRING, Types.LONG, Types.INT));

        resultDS.print();

        env.execute();
    }
}
